#include "stdafx.h"
#include "GameISC.h"
#include "ISCPacketCreator.h"

CGameISC::CGameISC(CISCSettings* settings, CGameServer* server)
	: m_settings(settings), m_server(server)
{
}

bool CGameISC::init(CNetwork* network)
{
	m_connection.Connector = network->createConnector();

	return m_connection.Connector != null;
}

bool CGameISC::run()
{
	if (!m_connection.Connector->isConnected())
	{
		if (m_connection.NextConnect == 0)
		{
			CConsole::print(" Lost connection to the CoreServer.\n");
			m_connection.NextConnect = CTime::seconds() + 3;
		}

		if (CTime::seconds() > m_connection.NextConnect)
		{
			if (m_connection.Connector->connect(m_settings->CoreIP.c_str(), m_settings->Port)
				&& m_connection.Connector->send(CISCPacketCreator::auth(m_settings->Password, m_settings->ServerIP, m_settings->ServerName, m_settings->MaxPlayers)))
			{
				m_connection.IsWaitingForAuthAnswer = true;
				m_connection.NextConnect = 0;
			}
			else
			{
				m_connection.NextConnect = CTime::seconds() + 3;
			}
		}
	}
	else if (!m_connection.Connector->incoming().empty())
	{
		while (_handlePacket());

		m_connection.Connector->incoming().clear();
	}

	return true;
}

bool CGameISC::_handlePacket()
{
	CByteArray &packet = m_connection.Connector->incoming();

	if(packet.getByte() != 0x6b)
		return false;

	uint packetSize = static_cast<uint>(packet.getInt());
	if (packetSize > packet.size() - 5)
		return false;

	int command = packet.getInt();

	switch (command)
	{
	case 0x02:
		_cmdHandler_authAnswer();
		break;

	default:
		{
#ifdef _DEBUG
			char buffer[256];
			sprintf(buffer, "Unknown_GameISC_%x.txt", command);
			packet.saveFormatted(buffer);
#endif
		}
		break;
	}

	return !packet.end();
}

void CGameISC::_cmdHandler_authAnswer()
{
	if (!m_connection.IsWaitingForAuthAnswer)
		return;

	m_connection.IsWaitingForAuthAnswer = false;

	CByteArray &packet = m_connection.Connector->incoming();

	m_connection.Id = packet.getInt();

	switch(packet.getByte())
	{
	case 1:
		CConsole::print(" Can't connect to the CoreServer: too many channels.\n");
		m_connection.Connector->close();
		break;

	case 2:
		CConsole::print(" Can't connect to the CoreServer: wrong ISC password.\n");
		m_connection.Connector->close();
		break;

	case 3:
		CConsole::print(" Successfully connected to the CoreServer.\n");
		break;
	}
}